package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EsManagerServiceImpl implements EsManagerService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private ESManagerMapper esManagerMapper;

    //创建索引库结构
    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    //导入全部sku集合进入到索引库
    @Override
    public void importAll() {
        //查询sku集合
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
        if (skuList == null || skuList.size() <= 0) {
            throw new RuntimeException("当前没有数据被查询到,无法导入到Es索引库");
        }
        //skuList转换成json
        String jsonSkuList = JSON.toJSONString(skuList);
        //将json转换成skuInfo
        List<SkuInfo> skuInfos = JSON.parseArray(jsonSkuList, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            //将规格信息转换成map
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfos);
    }

    //根据spuId查询skuList,添加到索引库
    @Override
    public void importBySpuId(String spuId) {
        //查询sku集合
        List<Sku> skuListBySpuId = skuFeign.findSkuListBySpuId(spuId);
        //判断查询结果
        if (skuListBySpuId == null || skuListBySpuId.size() <= 0) {
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }

        //将集合转换成json
        String jsonSkuLists = JSON.toJSONString(skuListBySpuId);
        //将JSON转换成SkuInfo
        List<SkuInfo> skuInfos = JSON.parseArray(jsonSkuLists, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            //将规格信息转换成map
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void deleteBySpuId(String spuId) {
        //查询sku集合
        List<Sku> skuListBySpuId = skuFeign.findSkuListBySpuId(spuId);
        //对查询结果进行判断
        if (skuListBySpuId == null || skuListBySpuId.size() <= 0) {
            throw new RuntimeException("当前没有数据被查询到,无法从索引库中删除");
        }

        for (Sku sku : skuListBySpuId) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
